#include "common.h"
#include "tpunb.h"
#include "recordModule.h"
#include "communicate.h"
#include "qtMessage.h"
#include "picPublish.h"
#include <signal.h>
#include <multi_select.h>
#include <mqtt_client.h>
#include <devnode.h>
#include <input_event.h>
#include <sys/prctl.h>
#include <sys/time.h>
#include <sys/resource.h>

#define MSG_QUEUE_KEY       		CONFIG_TOP_PATH"/key.txt"
#define MSG_QUEUE_ID       	 		'J'

static int msqid;

static void pre_init(void)
{
	if(isLinkFile("gw_info.json") || isLinkFile("dev_node_info.json")) {
		remove("gw_info.json");
		remove("dev_node_info.json");
		sync();

		myexec("mv /oem/gw_info.json gw_info.json", NULL, NULL);
		myexec("mv /oem/dev_node_info.json dev_node_info.json", NULL, NULL);
		sync();
	}
}

void qt_msg_send(void *msgp, int msgsz)
{
    msgsnd(msqid, msgp, msgsz, 0);
}

static void device_init(void)
{
    // 初始化窄带模组
    recordModuleInit();
    tpunbInit();
}

static void msg_queue_init(void)
{
	close(open(MSG_QUEUE_KEY, O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO));

    key_t key;
    key = ftok(MSG_QUEUE_KEY, MSG_QUEUE_ID);
    if (key < 0) {
        DEBUG("ftok");
        exit(EXIT_FAILURE);
    }

    msqid = msgget(key, 0664 | IPC_CREAT);
    if (msqid < 0) {
        DEBUG("msgget");
        exit(EXIT_FAILURE);
    }
}

void msg_queue_reset(void)
{
	int ret;
	msgbuf_t msg_buf = {0};

	while(1) {
		ret = msgrcv(msqid, &msg_buf, MSG_TEXT_LEN, 0, IPC_NOWAIT);
		if(ret >= 0) {
			DEBUG("msg_queue_reset");
			continue;
		}

		break;
	}
}

static void msg_queue_loop(void)
{
	int ret;
	msgbuf_t msg_buf = {0};

    while (1) {
        memset(&msg_buf, 0, sizeof(msg_buf));
		ret = msgrcv(msqid, &msg_buf, MSG_TEXT_LEN, MSG_CMD_DOWN, 0);
        if (ret < 0) {
            DEBUG("msgrcv error ret=%d", ret);
        } else {
            //处理QT消息队列
            qtMessageHandle(&msg_buf);
        }
    }
}

int main(int argc, char *argv[])
{
	DEBUG("VERSION:%s", VERSION);
	pre_init();
	system_init();
    device_init();
	input_dev_init();
	devnode_manage_init();
	tpunb_handler_init();
	msg_queue_init();	
	msg_queue_reset();
	msg_queue_loop();
    return 0;
}
